package com.arvinclub.web.controller.user;

import com.arvinclub.model.entity.User;
import com.arvinclub.service.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * 注册
 */
@Controller
public class RegisteController {
    @Resource
    private UserService userService;

    /**
     * 进入注册页面
     */
    @GetMapping("registe.html")
    public String registe(Model model) {
        model.addAttribute(new User());
        return "registe";
    }

    /**
     * 注册功能
     */
    @PostMapping("registe.html")
    public String registe(@Valid User user, Errors errors, HttpSession session, RedirectAttributes model) {
        /*检查用户名和密码是否为空*/
        if (errors.hasErrors())
            return "registe";
        /*不存在重名,则完成注册且自动登录*/
        if (!userService.existUserName(user.getName()) && userService.addUser(user)) {
            session.setAttribute("user", user);
            /*清除搜索的记录*/
            session.removeAttribute("blogList");
            session.removeAttribute("keyword");
            session.removeAttribute("page");
            return "redirect:user/blogs.html";
        }
        model.addFlashAttribute("msg", "err");
        return "redirect:registe.html";
    }
}
